package com.ruoyi.framework.web.service;

import javax.annotation.Resource;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.DesensitizedUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.log.StaticLog;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.LoginStatus;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.smsConfig.SmsCodeAuthenticationToken;
import com.ruoyi.pv.domain.PvUserInfo;
import com.ruoyi.pv.service.IPvUserInfoService;
import com.ruoyi.system.domain.WechatData;
import com.ruoyi.system.domain.WechatLoginBean;
import com.ruoyi.system.domain.WechatUser;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.IWechatUserService;
import com.ruoyi.system.utils.wechat.WechatUserUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Component;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.user.BlackListException;
import com.ruoyi.common.exception.user.CaptchaException;
import com.ruoyi.common.exception.user.CaptchaExpireException;
import com.ruoyi.common.exception.user.UserNotExistsException;
import com.ruoyi.common.exception.user.UserPasswordNotMatchException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.ip.IpUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.framework.security.context.AuthenticationContextHolder;

import java.util.concurrent.TimeUnit;

/**
 * 登录校验方法
 *
 * @author ruoyi
 */
@Component
public class SysLoginService {
    @Autowired private TokenService tokenService;

    @Resource private AuthenticationManager authenticationManager;
    @Resource private RedisCache redisCache;
    @Resource private SmsService smsService;
    @Resource private ISysUserService userService;
    @Resource private IPvUserInfoService userInfoService;
    @Resource private ISysConfigService configService;
    @Resource private WechatUserUtil wechatUserUtil;
    @Resource private IWechatUserService wechatUserService;
    @Resource private UserDetailsServiceImpl userDetailsService;

    /**
     * 获取微信的openId
     */
    public String getWxOpenId(String code) throws Exception{
        JSONObject openInfo = wechatUserUtil.getSessionKeyOrOpenId(code);
        if (StrUtil.isBlank(openInfo.getStr("openid"))){
            throw new ServiceException(openInfo.getStr("errmsg"),openInfo.getInt("errcode"));
        }
        //存入缓存
        String uuid = UUID.randomUUID().toString();
        String key = Constants.WECHAT_CODE_OPEN_INFO + uuid;
        redisCache.setCacheObject(key,openInfo,1,TimeUnit.MINUTES);
        return uuid;
    }

    public AjaxResult wechatLogin(WechatLoginBean loginBean) {
        AjaxResult ajax;
        //判断流程 如果是系统code,说明已经走过微信流程
        if (LoginStatus.isCode(loginBean.getCode())){
            //从缓存中获取用户信息
            String key = Constants.WECHAT_USER_INFO + loginBean.getUuid();
            if ("205".equals(loginBean.getCode())){
                ajax = userNotarize(loginBean,new WechatUser().setWechatData(loginBean.getRawData(),loginBean.getDeptId()));
            }else{
                WechatUser wechatUser = redisCache.getCacheObject(key);
                redisCache.deleteObject(key);//删除，下面流程会更新新的key
                ajax = ObjectUtil.isEmpty(wechatUser) ?
                        new AjaxResult(LoginStatus.UUID_PAST_DUE) : //直接提示过期
                        userNotarize(loginBean,wechatUser);//走确认信息流程
            }

        }else {//微信code
            String uuid = UUID.randomUUID().toString();
            //获取微信登录用户信息
            WechatUser wechatUser = wechatUserUtil.getUserInfo(loginBean);
            //将微信用户信息存储redis
            String key = Constants.WECHAT_USER_INFO + uuid;
            redisCache.setCacheObject(key,wechatUser,10,TimeUnit.MINUTES);

            Long deptId = wechatUser.getDeptId();
            //先根据手机号查询系统用户
            SysUser sysUser = userService.selectUserByPhone(wechatUser.getMobile());
            if (ObjectUtil.isNotEmpty(sysUser)){//存在
                //根据openid查询微信用户信息,微信注册信息存在，说明已经注册过，直接登录，如果没有，前端确认信息后登录
                wechatUser.setId(sysUser.getUserId());
                if (ObjectUtil.isNotEmpty(wechatUserService.selectWechatUserById(sysUser.getUserId()))){
                    // 修改用户信息
                    wechatUserService.updateWechatUser(wechatUser);
                    //登录
                    ajax = new AjaxResult(LoginStatus.SUCCESS).token(weChatLogin(sysUser,deptId));
                }else {
                    ajax = new AjaxResult(LoginStatus.WECHAT_NOT_HAS).
                           put("nickName",sysUser.getNickName()).
                           put("postsNumber",sysUser.getPostsNumber()).uuid(uuid);
                }
            }else {
               //前端提示用户自己输入上岗证和姓名
                ajax = new AjaxResult(LoginStatus.USER_NOT_HAS).uuid(uuid);
            }
        }
        return ajax;
    }

    /**
     * 确认信息流程
     * 201 ： 用户信息存在，微信注册信息不存在        【请确认上岗证和姓名】
     * 202 : 用户信息不存在，需要提示用户自己输入上岗证和姓名，再联合搜索，    【用户信息不存在，请输入上岗证、姓名】
     *       如果上岗证和信息没有查到，登录失败
     *       如果查到，说明手机号不对，提示【已有绑定手机号，是否更换手机】
     * 203 : 发送验证码【该上岗证已有绑定用户，是否更换手机号】
     * 204 : 验证验证码 【发送成功】
     * 205 : 默认注册流程，需要用户输入姓名等信息
     */
    private AjaxResult userNotarize(WechatLoginBean loginBean,WechatUser wechatUser){
        StaticLog.info("bean:{}", JSONUtil.toJsonPrettyStr(loginBean));
        AjaxResult ajax;
        String code = loginBean.getCode();
        Long deptId = wechatUser.getDeptId();
        SysUser sysUser;
        switch (code){
            case "201":{
                sysUser = userService.selectUserByPhone(wechatUser.getMobile());
                //登录
                ajax =  new AjaxResult(LoginStatus.SUCCESS).token(weChatLogin(sysUser,deptId));
            }break;
            case "202":{
                WechatData rawData = loginBean.getRawData();
                sysUser = userService.selectUserByNickNameAndPostsNumberAndDeptId(rawData.getNickName(), rawData.getPostsNumber(), deptId);
                if (ObjectUtil.isEmpty(sysUser)){
                    ajax = new AjaxResult(LoginStatus.FAIL);
                }else{
                    String phonenumber = sysUser.getPhonenumber();
                    if (phonenumber.equals(wechatUser.getMobile())){
                        ajax = new AjaxResult(LoginStatus.SUCCESS).token(weChatLogin(sysUser, deptId));
                    }else{
                        String uuid = UUID.randomUUID().toString();
                        //更新用户缓存
                        wechatUser.setNickname(rawData.getNickName());
                        wechatUser.setPostsNumber(rawData.getPostsNumber());
                        redisCache.setCacheObject(Constants.WECHAT_USER_INFO + uuid,wechatUser,10,TimeUnit.MINUTES);
                        //存入redis
                        redisCache.setCacheObject(Constants.WECHAT_USER_CHANGE_MOBILE + uuid,phonenumber,5,TimeUnit.MINUTES);
                        ajax = new AjaxResult(LoginStatus.USER_PHONE_AIL).put("mobile", DesensitizedUtil.mobilePhone(phonenumber)).uuid(uuid);
                    }
                }
            }break;
            case "203":{
                //确认发送短信
                String key = Constants.WECHAT_USER_CHANGE_MOBILE + loginBean.getUuid();
                String phonenumber = redisCache.getCacheObject(key);
                StaticLog.info("phonenumber{}",phonenumber);
                if (StrUtil.isBlank(phonenumber)){
                    ajax = new AjaxResult(LoginStatus.UUID_PAST_DUE);
                }else{
                    String uuid = smsService.sendSmsCode(phonenumber, false);
                    //更新 uuid
                    redisCache.deleteObject(key);
                    key = Constants.WECHAT_USER_CHANGE_MOBILE + uuid;
                    redisCache.setCacheObject(key,phonenumber,5,TimeUnit.MINUTES);
                    //更新用户缓存
                    redisCache.setCacheObject(Constants.WECHAT_USER_INFO + uuid,wechatUser,10,TimeUnit.MINUTES);
                    ajax = new AjaxResult(LoginStatus.SUCCESS_SMS).uuid(uuid).put("smsCode",redisCache.getCacheObject(Constants.SMS_CAPTCHA_CODE_KEY + uuid));
                }
            }break;
            case "204":{
                String uuid = loginBean.getUuid();
                String phonenumber = redisCache.getCacheObject(Constants.WECHAT_USER_CHANGE_MOBILE + uuid);
                //验证验证码
                smsService.checkSmsCode(phonenumber,loginBean.getSmsCode(),uuid);
                //更新用户信息
                sysUser = userService.selectUserByNickNameAndPostsNumberAndDeptId(wechatUser.getNickname(), wechatUser.getPostsNumber(), deptId);
                userService.updateUser(SysUser.builder().userId(sysUser.getUserId()).phonenumber(wechatUser.getMobile()).build());
                //添加微信注册信息
                wechatUser.setId(sysUser.getUserId());
                if (ObjectUtil.isEmpty(wechatUserService.selectWechatUserById(sysUser.getUserId()))){
                    wechatUserService.insertWechatUser(wechatUser);
                }else{
                    wechatUserService.updateWechatUser(wechatUser);
                }
                ajax = new AjaxResult(LoginStatus.SUCCESS).token(weChatLogin(sysUser,deptId));
            }break;
            case "205":{
                WechatData userData = loginBean.getRawData();
                //验证验证码
                smsService.checkSmsCode(userData.getMobile(),loginBean.getSmsCode(),loginBean.getUuid());
                if (ObjectUtil.isEmpty(userData) && ObjectUtil.isEmpty(userData.getNickName())){
                    ajax = AjaxResult.error("姓名不可为空");
                }else{
                    sysUser = new SysUser();
                    sysUser.setNickName(userData.getNickName());
                    //校验
                    sysUser.setUserType("2");
                    sysUser.setPhonenumber(userData.getMobile());//手机号
                    sysUser.setUserName(userData.getMobile());//使用手机号码做登录名
                    sysUser.setPassword("$2a$10$0NZYIllzgtXtxjNpogc4K.h8CT0C1i4vJA1fb/FzjYBODD4gVuchC");//默认密码 【123456】
                    sysUser.setDeptId(deptId);//机构
                    sysUser.setBirthday(userData.getBirthday());
                    //注册
                    userService.registerUser(sysUser);
                    PvUserInfo userInfo = BeanUtil.copyProperties(userData, PvUserInfo.class);
                    userInfo.setId(sysUser.getUserId());
                    userInfoService.insertPvUserInfo(userInfo);
                    //wechatUser.setId(sysUser.getUserId());//保持一致
                    //添加微信用户
                    //wechatUserService.insertWechatUser(wechatUser);
                    ajax = new AjaxResult(LoginStatus.SUCCESS).token(login(sysUser.getUserName(), "123456",null,null, deptId));
                }
            }break;
            default: ajax = AjaxResult.error("code有误");
        }
        return ajax;
    }

    private String weChatLogin(SysUser sysUser, Long deptId){
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(sysUser.getUserName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        //校验机构
        if (!deptId.equals(sysUser.getDeptId())) {
            throw new GlobalException("机构校验失败");
        }
        recordLoginInfo(sysUser.getUserId());
        // 生成token
        return tokenService.createToken(userDetailsService.createLoginUser2(sysUser));
    }

    //------------------------------------------------------------------------------------------------------------------------------------------

    /**
     * 登录验证
     * @param username 用户名
     * @param password 密码
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public String login(String username, String password, String code, String uuid, Long deptId) {
        // 验证码校验
        validateCaptcha(username, code, uuid);
        // 登录前置校验
        loginPreCheck(username, password);
        // 用户验证
        Authentication authentication = null;
        try {
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
            AuthenticationContextHolder.setContext(authenticationToken);
            // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(authenticationToken);
        } catch (Exception e) {
            if (e instanceof BadCredentialsException) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
                throw new UserPasswordNotMatchException();
            } else {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
                throw new ServiceException(e.getMessage());
            }
        } finally {
            AuthenticationContextHolder.clearContext();
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        //校验机构
        if (!deptId.equals(loginUser.getDeptId())) {
            throw new GlobalException("机构校验失败");
        }
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 手机号登录验证
     * @param mobile 手机号
     * @param code   验证码
     * @param uuid   唯一标识
     * @return 结果
     */
    public String smsLogin(String mobile, String code, String uuid) {
        // 用户验证
        Authentication authentication = null;
        try {
            smsService.checkSmsCode(mobile, code, uuid);
            // 该方法会去调用SmsUserDetailsServiceImpl.loadUserByUsername
            authentication = authenticationManager.authenticate(new SmsCodeAuthenticationToken(mobile));
        } catch (Exception e) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(mobile, Constants.LOGIN_FAIL, e.getMessage()));
            throw new ServiceException(e.getMessage());
        }
        AsyncManager.me().execute(AsyncFactory.recordLogininfor(mobile, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        recordLoginInfo(loginUser.getUserId());
        // 生成token
        return tokenService.createToken(loginUser);
    }

    /**
     * 校验验证码
     *
     * @param username 用户名
     * @param code     验证码
     * @param uuid     唯一标识
     * @return 结果
     */
    public void validateCaptcha(String username, String code, String uuid) {
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        if (captchaEnabled) {
            String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
            String captcha = redisCache.getCacheObject(verifyKey);
            redisCache.deleteObject(verifyKey);
            if (captcha == null) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
                throw new CaptchaExpireException();
            }
            if (!code.equalsIgnoreCase(captcha)) {
                AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
                throw new CaptchaException();
            }
        }
    }

    /**
     * 登录前置校验
     *
     * @param username 用户名
     * @param password 用户密码
     */
    public void loginPreCheck(String username, String password) {
        // 用户名或密码为空 错误
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
            throw new UserNotExistsException();
        }
        // 密码如果不在指定范围内 错误
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // 用户名不在指定范围内 错误
        if (username.length() < UserConstants.USERNAME_MIN_LENGTH
                || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
            throw new UserPasswordNotMatchException();
        }
        // IP黑名单校验
        String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
            throw new BlackListException();
        }
    }

    /**
     * 验证学生的姓名和上岗证是否存在
     */
    private void nickNameAndPostsNumberCheck(SysUser sysUser){
        if (StrUtil.hasBlank(sysUser.getNickName(),sysUser.getNickName())){
            throw new GlobalException("姓名和上岗证编号不可为空");
        }
    }
    /**
     * 记录登录信息
     *
     * @param userId 用户ID
     */
    public void recordLoginInfo(Long userId) {
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        sysUser.setLoginIp(IpUtils.getIpAddr());
        sysUser.setLoginDate(DateUtils.getNowDate());
        userService.updateUserProfile(sysUser);
    }



}
